<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="4.25rem"
    >
      <el-form-item label="商品名称" prop="goodName">
        <el-input
          v-model="queryParams.goodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="店铺名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入店铺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
        <!-- <el-select v-model="queryParams.storeName" clearable filterable placeholder="请选择">
          <el-option v-for="item in shopList" :key="item.id" :label="item.storeName" :value="item.storeName">
          </el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="isDisplayed">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleaddGoodOpen()"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:good:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:good:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          v-hasPermi="['system:good:import']"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:good:export']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="goodList"
      @selection-change="handleSelectionChange"
      height="42.5rem"
      :row-class-name="tableRowClassName"
      row-key="goodId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
      <el-table-column
        label="商品名称"
        align="center"
        prop="goodName"
        width="150"
      />
      <el-table-column label="店铺信息" prop="storeName" width="200">
        <template slot-scope="r">
          <div>名称：{{ r.row.storeName }}</div>
          <div>地址：{{ r.row.storeAddress }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品图片"
        align="center"
        prop="goodImg"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodImg" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="商品价格" align="center" prop="retailPrice" />
      <el-table-column label="会员价" align="center" prop="memberPrice" />
      <!-- <el-table-column label="详情" align="center" prop="goodDetail" :show-overflow-tooltip='true' /> -->
      <el-table-column
        label="供应商"
        align="center"
        prop="isInitiate"
        width="150"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.source == 1">{{ scope.row.supplierName }}</span>
          <span v-if="scope.row.source == 2"></span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建者" align="center" prop="createUser" /> -->
      <el-table-column
        label="剩余数量"
        align="center"
        prop="counts"
        style="color: red"
      />
      <el-table-column
        label="累计销售数量"
        align="center"
        prop="totalSellCount"
        width="100"
      />
      <el-table-column label="月售" align="center" prop="monthSellCount" />
      <el-table-column
        label="审核状态"
        align="center"
        prop="monthSellCount"
        width="100"
      >
        <template slot-scope="{ row }">
          <div v-if="row.goodStatus == 1">待审核</div>
          <div v-if="row.goodStatus == 2">审核通过</div>
          <div v-if="row.goodStatus == 3" style="color: red">审核未通过</div>
        </template>
      </el-table-column>

      <el-table-column label="采购来源" align="center" prop="source">
        <template slot-scope="scope">
          <span v-if="scope.row.source == 1" style="color: blue">采购</span>
          <span v-if="scope.row.source == 2" style="color: burlywood"
            >店铺自加</span
          >
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isInitiate">
        <template slot-scope="scope">
          <span
            v-if="scope.row.isInitiate == 0"
            style="color: green; font-weight: bold"
            >已上架</span
          >
          <span
            v-if="scope.row.isInitiate == 1"
            style="color: gray; font-weight: bold"
            >未上架</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="商品条形码"
        align="center"
        prop="goodImg"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview :src="scope.row.qrCodeUrl" :width="50" :height="50" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <!-- <el-table-column label="版本号" align="center" prop="version" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="230"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.goodStatus == 1"
            @click="setGoodAudit(scope.row, 'ok')"
            v-hasPermi="['system:good:auditBy']"
            >审核通过</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.goodStatus == 1"
            @click="setGoodAudit(scope.row)"
            v-hasPermi="['system:good:auditNoBy']"
            >审核未通过</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.isInitiate == 1 && scope.row.goodStatus == 2"
            @click="handleUp(scope.row)"
            v-hasPermi="['system:good:listed']"
            >上架</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleDown(scope.row)"
            v-if="scope.row.isInitiate == 0 && scope.row.goodStatus == 2"
            v-hasPermi="['system:good:removed']"
            >下架</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleaddGoodOpen(scope.row)"
            v-if="scope.row.parentId == 0 && isDisplayed"
            v-hasPermi="['system:good:updata']"
            >添加规格</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
            v-if="scope.row.source == 2"
            v-hasPermi="['system:good:updata']"
            >修改</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.source !== 1"
            v-hasPermi="['system:good:replenishment']"
            >补货</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="printerBarcode(scope.row)"
            v-hasPermi="['system:good:barcode']"
            >打印条形码</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:good:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      :visible.sync="addOpen"
      width="62.5rem"
      append-to-body
    >
      <el-form
        ref="goodform"
        :model="goodform"
        :rules="rules"
        label-width="5rem"
      >
        <el-row v-if="goodform.parentId === 0 || !goodform.parentId">
          <el-col :span="8">
            <el-form-item
              label="一级分类"
              prop="classOneId"
              v-if="title != '添加商品规格' && title != '修改商品规格'"
            >
              <el-select
                v-model="goodform.classOneId"
                placeholder="请选择"
                @change="getline"
              >
                <el-option
                  v-for="item in goodclassifyListOne"
                  :key="item.id"
                  :label="item.deptName"
                  :value="item.id"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="form.classOneId" placeholder="请输入" /> -->
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="二级分类" prop="classTwoId">-->
          <!--              <el-select v-model="goodform.classTwoId" placeholder="请选择" @change="getlineTwo">-->
          <!--                <el-option v-for="item in goodclassifyListTwo" :key="item.id" :label="item.deptName"-->
          <!--                  :value="item.id"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <!--          <el-col :span="8">-->
          <!--            <el-form-item label="三级分类" prop="classThreeId">-->
          <!--              <el-select v-model="goodform.classThreeId" placeholder="请选择" @change="getlineThree">-->
          <!--                <el-option v-for="item in goodclassifyListThree" :key="item.id" :label="item.deptName"-->
          <!--                  :value="item.id"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item
              label="品牌"
              prop="brand"
              v-if="title != '添加商品规格' && title != '修改商品规格'"
            >
              <el-input v-model="goodform.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="产地"
              v-if="title != '添加商品规格' && title != '修改商品规格'"
            >
              <el-input v-model="goodform.place" placeholder="请输入产地" />
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="title == '添加店铺商品' ? '商品名称' : '规格名称'"
              prop="goodName"
            >
              <el-input v-model="goodform.goodName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item
              label="商品卖点"
              prop="sellingPoints"
              v-if="title != '添加商品规格' && title != '修改商品规格'"
            >
              <el-input
                v-model="goodform.sellingPoints"
                placeholder="请输入商品卖点"
              />
            </el-form-item> -->
            <!-- <el-form-item label="商品模板">
              <el-select v-model="goodNameMuban" filterable placeholder="请选择商品模板" style="width: 97.5%;"
                @change="getlineFour">
                <el-option v-for="item in goodclassifyListFour" :key="item.goodName" :label="item.goodName"
                  :value="item.goodName"></el-option>
              </el-select>
            </el-form-item>-->
          </el-col>
        </el-row>
        <el-form-item
          :label="
            title == '添加店铺商品' || title == '修改店铺商品'
              ? '商品图片'
              : '规格图片'
          "
          prop="goodImg"
        >
          <image-upload v-model="goodform.goodImg" />
        </el-form-item>
        <el-form-item
          label="详情图片"
          prop="goodDetail"
          v-if="title == '添加店铺商品'"
        >
          <image-upload v-model="goodform.goodDetail" />
        </el-form-item>
        <!-- <el-form-item
          label="详情描述"
          prop="goodText"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input
            v-model="goodform.goodText"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item> -->
        <!-- <el-form-item label="详情">
          <editor v-model="goodform.goodDetail" :min-height="192" />
        </el-form-item> -->
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item
              label="批发价"
              prop="tradePrice"
              v-if="title == '添加商品规格' || title == '修改商品规格'"
            >
              <el-input
                v-model="goodform.tradePrice"
                placeholder="请输入批发价"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item
              label="零售价"
              prop="retailPrice"
              v-if="title == '添加商品规格' || title == '修改商品规格'"
            >
              <el-input
                v-model="goodform.retailPrice"
                placeholder="请输入零售价"
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="8">
            <el-form-item label="会员价" prop="memberPrice">
              <el-input v-model="goodform.memberPrice" placeholder="请输入会员价" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item
              label="库存"
              prop="counts"
              v-if="title == '添加商品规格' || title == '修改商品规格'"
            >
              <el-input
                v-model="goodform.counts"
                placeholder="请输入库存数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item
          label="单位[计量]"
          prop="units"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input v-model="goodform.units" placeholder="请输入单位" />
        </el-form-item> -->
        <div v-for="(item, i) in goodform.paramsNewArr" :key="i">
          <el-row v-if="title != '添加商品规格' && title != '修改商品规格'">
            <el-col :span="10">
              <el-form-item
                label="参数名称"
                :prop="`paramsNewArr[${i}].paramsName`"
                :rules="[
                  {
                    required: true,
                    message: '输入参数名称',
                    trigger: 'change',
                  },
                ]"
              >
                <el-input v-model="item.paramsName" placeholder="请输入单位" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="参数内容">
                <el-input v-model="item.paramsValue" placeholder="请输入单位" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <div>
                <i
                  style="
                    cursor: pointer;
                    margin-left: 6px;
                    margin-top: 5px;
                    font-size: 20px;
                  "
                  v-if="goodform.paramsNewArr.length > 1"
                  class="el-icon-remove-outline"
                  @click="del(i)"
                ></i>
                <i
                  style="
                    cursor: pointer;
                    margin-left: 6px;
                    margin-top: 5px;
                    font-size: 20px;
                  "
                  class="el-icon-circle-plus-outline"
                  @click="add"
                ></i>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- <el-form-item
          label="重量"
          prop="weight"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input v-model="goodform.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item
          label="重量单位"
          prop="weightUnits"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input
            v-model="goodform.weightUnits"
            placeholder="请输入重量单位"
          />
        </el-form-item>
        <el-form-item
          label="店内码"
          prop="articleNumber"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input
            v-model="goodform.articleNumber"
            placeholder="请输入店内码"
          />
        </el-form-item>
        <el-form-item
          label="货架码"
          prop="shelfCode"
          v-if="title == '添加商品规格' || title == '修改商品规格'"
        >
          <el-input v-model="goodform.shelfCode" placeholder="请输入货架码" />
        </el-form-item> -->
        <!-- <el-form-item label="起购数" prop="minimumPurchaseQuantity" v-if="title == '添加商品规格子商品'">
          <el-input v-model="goodform.minimumPurchaseQuantity" placeholder="请输入起购数" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goodsubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--
    <el-dialog :title="buytitle" :visible.sync="buyopen" width="31.25rem" append-to-body>
      <el-form ref="buyform" :model="buyform" :rules="buyrules" label-width="5rem">
        <el-form-item label="采购数量" prop="counts">
          <el-input v-model="buyform.counts" placeholder="请输入采购数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="buySubmitForm">确 定</el-button>
        <el-button @click="buyCancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <!-- 添加或修改店铺商品对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="31.25rem"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="5rem">
        <!-- <el-form-item label="供应商商品id" prop="goodId">
          <el-input v-model="form.goodId" placeholder="请输入供应商商品id" />
        </el-form-item>
        <el-form-item label="创建者" prop="createUser">
          <el-input v-model="form.createUser" placeholder="请输入创建者" />
        </el-form-item> -->

        <el-form-item label="补货数量" prop="counts">
          <el-input v-model="form.counts" placeholder="请输入补货数量" />
        </el-form-item>

        <!-- <el-form-item label="配送方式" prop="deliveryType">
          <el-select v-model="form.deliveryType" placeholder="请选择配送方式">
            <el-option v-for="item in deliveryList"
              :key="item.id"
              :label="item.label"
              :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="配送费" prop="deliveryCost">
          <el-input v-model="form.deliveryCost" disabled  />
        </el-form-item> -->

        <!-- <el-form-item label="累计销售数量" prop="totalSellCount">
          <el-input v-model="form.totalSellCount" placeholder="请输入累计销售数量" />
        </el-form-item>
        <el-form-item label="店铺id" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入店铺id" />
        </el-form-item> -->
        <!-- <el-form-item label="月售" prop="monthSellCount">
          <el-input v-model="form.monthSellCount" placeholder="请输入月售" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <!-- <el-form-item label="版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入版本号" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formNaNpxark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Barcode :codeDetail="codeDetail" ref="barcode" />
    <!-- 导入商品模板对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGood,
  getGood,
  delGood,
  addGood,
  updateGood,
  addstoreGood,
  replenishment,
  replenish,
  updatastoreGood,
  goodAudit,
} from "@/api/fx/storegood";
import { listStore } from "@/api/fx/store.js";
import { listGoodclassify } from "@/api/fx/goodclassify";
import { listArea } from "@/api/fx/goodArea";
import { getToken } from "@/utils/auth";
import {
  threeSelectModel,
  fourSelectModel,
  hierarchySelectModel,
} from "@/api/fx/model";
import Cookies from "js-cookie";

export default {
  name: "Good",
  data() {
    const validatePrice = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("价格不能为空"));
      } else if (!/^(0\.(0[1-9]|[1-9]\d*)|[1-9]\d*\.?\d*)$/.test(value)) {
        callback(new Error("价格必须大于0.01"));
      } else {
        callback();
      }
    };
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/fx/store/good/importDp",
      },
      goodNameMuban: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      goodIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺商品表格数据
      goodList: [],
      goodAreas: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      addOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isInitiate: null,
      },
      // 表单参数
      form: {},
      goodform: {
        units: null,
        paramsNewArr: [{ paramsName: "", paramsValue: "" }],
      },
      goodclassifyList: [],
      goodclassifyListOne: [],
      goodclassifyListTwo: [],
      goodclassifyListThree: [],
      goodclassifyListFour: [],
      goodclassifyListFours: [],
      // 表单校验
      rules: {
        counts: [
          { required: true, message: "补货数量不能为空", trigger: "blur" },
        ],
        classOneId: [
          { required: true, message: "一级分类不能为空", trigger: "blur" },
        ],
        classTwoId: [
          { required: true, message: "二级分类不能为空", trigger: "blur" },
        ],
        classThreeId: [
          { required: true, message: "三级分类不能为空", trigger: "blur" },
        ],
        goodName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        goodImg: [
          { required: true, message: "商品图片不能为空", trigger: "blur" },
        ],
        tradePrice: [
          { required: true, message: "批发价不能为空", trigger: "blur" },
          { validator: validatePrice, trigger: "blur" },
        ],
        retailPrice: [
          { required: true, message: "零售价不能为空", trigger: "blur" },
          { validator: validatePrice, trigger: "blur" },
        ],
        memberPrice: [
          { required: true, message: "会员价不能为空", trigger: "blur" },
          { validator: validatePrice, trigger: "blur" },
        ],
        counts: [
          { required: true, message: "库存数量不能为空", trigger: "blur" },
        ],
      },
      //是否运行新增
      isDisplayed: false,
      deliveryList: [
        {
          id: 1,
          label: "普通配送",
        },
        {
          id: 2,
          label: "加急配送",
        },
      ],
      shopList: [],
      formNaNpxark: "",
      isAdd: true,
      codeDetail: {},
      printerCount: 0,
      goodsImg: null,
    };
  },
  created() {
    this.getList();
    this.getlistGoodclassify();
    this.getGoodlistArea();
    this.getShopList();

    const roles = JSON.parse(Cookies.get("roles"));
    roles.forEach((item) => {
      if (item == "store") {
        this.isDisplayed = true;
      }
    });
  },
  methods: {
    //添加评价内容
    add() {
      this.goodform.paramsNewArr.push({ paramsName: "", paramsValue: "" });
    },
    //删除评价内容
    del(i) {
      this.goodform.paramsNewArr.splice(i, 1);
    },

    // 获取店铺信息
    getShopList() {
      let query = {
        pageNum: 1,
        pageSize: 9999,
        status: 1,
      };
      listStore(query).then((res) => {
        if (res.code == 200) {
          this.shopList = res.rows;
        }
      });
    },

    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.name === "李四") {
        // 返回样式对象
        return { backgroundColor: "yellow" };
      }
      // 或者返回空对象，表示不应用任何样式
      return { backgroundColor: "yellow" };
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.counts < 50) {
        return "highlight-row";
      }
      return "";
    },
    getGoodlistArea() {
      listArea(this.queryParams).then((response) => {
        this.goodAreas = response.rows;
        console.log(this.goodAreas);
      });
    },

    // 打印条形码
    printerBarcode(row) {
      if (this.$refs["barcode"].detectionPrinter()) return;
      if (this.$refs["barcode"].updatePrinterList()) return;
      this.$prompt("请输入打印张数： ", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[1-9]\d*$/,
        inputPlaceholder: "请输入正整数",
        inputErrorMessage: "输入的内容不是一个数字或不是一个正整数!",
        inputValue: null,
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "打印中...";
            instance.confirmButtonLoading = false;
            setTimeout(() => {
              setTimeout(() => {
                done();
              }, 300);
            }, 3000);
          } else {
            done();
          }
        },
      })
        .then(({ value }) => {
          this.codeDetail = { ...row, count: value };
          this.$message({
            type: "success",
            message: "打印中...",
          });
        })
        .catch((e) => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: '',
      //   message: h('p', { style: 'padding: 20px 0' }, [
      //     h('span', null, '请输入打印张数： '),
      //     // h('el-input-number', { ref: 'printerCount', style: 'width: 70%' }, null)
      //     h('el-input-number', { ref: 'printerCount' }, null)
      //   ]),
      //   // showInput: false,
      //   showCancelButton: true,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   // inputPlaceholder: '请输入正整数',
      //   // inputErrorMessage: '输入的内容不是一个数字或不是一个正整数!',
      //   // inputPattern: /^[1-9]\d*$/,
      //   beforeClose: (action, instance, done) => {
      //     if (action === 'confirm') {
      //       if (!this.$refs['printerCount'].currentValue) {
      //         this.$message.warning('打印张数不能为空！')
      //         return
      //       }
      //       instance.confirmButtonLoading = true;
      //       instance.confirmButtonText = '打印中...';
      //       this.codeDetail = { ...row, count: this.$refs['printerCount'].currentValue }
      //       setTimeout(() => {
      //         // this.$refs['printerCount'].currentValue = 0
      //         done();
      //         setTimeout(() => {
      //           instance.confirmButtonLoading = false;
      //         }, 300);
      //       }, 3000);
      //     } else {
      //       // this.$refs['printerCount'].currentValue = 0
      //       done();
      //     }
      //   }
      // }).then(action => {

      // });
    },

    /** 查询店铺商品列表 */
    getList() {
      this.loading = true;
      listGood(this.queryParams).then((response) => {
        this.goodList = this.handleTree(response.rows, "goodId");
        this.total = response.total;
        this.loading = false;
      });
    },

    getlistGoodclassify() {
      listGoodclassify(this.queryParams).then((response) => {
        this.goodclassifyList = response.rows;
        this.goodclassifyListOne = this.goodclassifyList.filter(
          (item) => item.tier == 0
        );
        this.goodclassifyListTwo = this.goodclassifyList.filter(
          (item) => item.tier == 1
        );
        this.goodclassifyListThree = this.goodclassifyList.filter(
          (item) => item.tier == 2
        );
      });
    },
    getline(row) {
      this.goodclassifyListTwo = this.goodclassifyList.filter(
        (item) => item.parentId == parseInt(row)
      );
      // this.goodform.classTwoId = '';
    },
    getlineTwo(row) {
      this.goodclassifyListThree = this.goodclassifyList.filter(
        (item) => item.parentId == parseInt(row)
      );
      this.form.classThreeId = "";
    },
    getlineThree(row) {
      let oneId = this.goodform.classOneId;
      // let twoId = this.goodform.classTwoId

      hierarchySelectModel(row).then((res) => {
        console.log(res, "根据最后一级id查询模板");
        if (res.code == 200) {
          this.goodsImg = res.data.goodImg;
          this.goodform.goodName = res.data.goodName;
          this.goodform.goodImg = this.goodsImg;
          this.goodclassifyListFour = [...res.data.modelList];
          this.goodclassifyListFours = [...res.data.modelList];
          this.goodform.classOneId = oneId;
          // this.goodform.classTwoId = twoId
          // this.goodform.classThreeId = row
        }
      });
    },
    getlineFour(row) {
      let detail = this.goodclassifyListFour.filter(
        (item) => item.goodName == row
      );
      if (
        detail[0].specificationsList &&
        detail[0].specificationsList.length != 0
      ) {
        detail[0].paramsNewArr = [];
        detail[0].specificationsList.map((el) => {
          detail[0].paramsNewArr.push({
            paramsName: el.split(",")[0],
            paramsValue: el.split(",")[1],
          });
        });
      } else {
        detail[0].paramsNewArr = [
          {
            paramsName: "",
            paramsValue: "",
          },
        ];
      }
      let newForm = JSON.parse(JSON.stringify(this.goodform));
      this.goodform = Object.assign(newForm, detail[0]);
    },
    formFilterMethod(row) {
      let list = [];
      this.goodclassifyListFours.forEach((item) => {
        if (item.goodName.indexOf(row) !== -1) {
          list.push(item);
        }
      });
      this.goodclassifyListFour = list;
      // if (list.length == 0) {
      //   this.goodclassifyListFour = [...this.goodclassifyListFours]
      // } else {
      // }
      this.$set(this.goodform, "goodName", row);
      let newForm = {
        goodImg: this.goodsImg,
        goodDetail: "",
        goodText: "",
        tradePrice: "",
        retailPrice: "",
        memberPrice: "",
      };
      Object.assign(this.goodform, newForm);
    },
    saveFormclass(row) {
      let oneName = this.goodclassifyListOne.filter(
        (item) => this.form.oneId == item.id
      )[0]?.deptName;
      let twoName = this.goodclassifyListTwo.filter(
        (item) => item.id == this.form.twoId
      )[0]?.deptName;
      let oneId = this.form.oneId;
      let twoId = this.form.twoId;
      this.form = {};
      this.form.oneId = oneId;
      this.form.twoId = twoId;
      this.form.classifyId = row;
      this.form.oneName = oneName;
      this.form.twoName = twoName;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.addOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodId: null,
        createTime: null,
        createUser: null,
        remark: null,
        counts: null,
        totalSellCount: null,
        storeId: null,
        monthSellCount: null,
        delFlag: null,
        isInitiate: null,
        version: null,
      };
      this.goodform = {
        id: null,
        userId: null,
        goodName: null,
        goodDesc: null,
        tradePrice: null,
        retailPrice: null,
        createTime: null,
        createUser: null,
        remark: null,
        region: null,
        grandCounts: null,
        counts: null,
        totalSellCount: null,
        goodImg: null,
        goodDetail: null,
        goodText: null,
        qrCodeUrl: null,
        status: null,
        classOneId: null,
        classTwoId: null,
        classThreeId: null,
        classOneName: null,
        classTwoName: null,
        classThreeName: null,
        delFlag: null,
        isInitiate: null,
        version: null,
        units: null,
        weight: null,
        weightUnits: null,
        articleNumber: null,
        shelfCode: null,
        minimumPurchaseQuantity: null,
        paramsNewArr: [{ paramsName: "", paramsValue: "" }],
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.goodIds = selection.map((item) => item.goodId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleaddGoodOpen(row) {
      this.reset();
      this.addOpen = true;
      this.title = "添加店铺商品";
      this.isAdd = true;
      if (row) {
        this.goodform.parentId = row.goodId;
        this.goodform.classOneId = row.classOneId;
        this.goodform.region = row.region;
        this.goodform.regionName = row.regionName;
        this.goodform.regionArr = row.regionArr;
        this.title = "添加商品规格";
      }
      console.log(this.goodform);
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺商品";
    },
    // 审核商品
    setGoodAudit(row, type) {
      let params = {
        id: row.id,
        status: null,
      };
      if (type) {
        params.status = 2;
      } else {
        params.status = 3;
      }
      goodAudit(params).then((res) => {
        if (res.code == 200) {
          if (type) {
            this.$message.success("该商品已通过审核");
          } else {
            this.$message.error("该商品未通过审核");
          }
          this.getList();
        }
      });
    },
    /** 上架按钮操作 */
    handleUp(row) {
      const goodid = row.id;
      let obj = {
        id: goodid,
        isInitiate: 0,
        source: row.source,
      };
      updateGood(obj).then((response) => {
        this.$modal.msgSuccess("已上架");
        this.getList();
      });
    },
    /** 下架按钮操作 */
    handleDown(row) {
      const goodid = row.id;
      let obj = {
        id: goodid,
        isInitiate: 1,
        source: row.source,
      };
      updateGood(obj).then((response) => {
        this.$modal.msgSuccess("已下架");
        this.getList();
      });
    },
    /** 补货按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getGood(id).then((response) => {
        this.form = response.data;
        this.form.counts = "";
        this.formNaNpxark = "";
        this.open = true;
        this.title = "店铺商品补货信息";
      });
    },
    revertData(convertedData) {
      const newDataList = [];
      const pairs = convertedData.split("。");
      pairs.forEach((pair) => {
        // 同时支持中文冒号和英文冒号
        const separatorIndex = pair.includes("：")
          ? pair.indexOf("：")
          : pair.indexOf(":");

        // 确保找到了分隔符且键名存在
        if (separatorIndex !== -1 && separatorIndex > 0) {
          const paramsName = pair.substring(0, separatorIndex).trim();
          const valuesStr = pair.substring(separatorIndex + 1).trim();

          // 忽略空值
          if (valuesStr) {
            if (valuesStr.includes(",")) {
              // 多值情况：按逗号拆分
              const values = valuesStr.split(",");
              values.forEach((value) => {
                const trimmedValue = value.trim();
                if (trimmedValue) {
                  newDataList.push({
                    paramsName,
                    paramsValue: trimmedValue,
                  });
                }
              });
            } else {
              // 单值情况：直接添加
              newDataList.push({
                paramsName,
                paramsValue: valuesStr,
              });
            }
          }
        }
      });

      return newDataList;
    },

    //修改
    handleDetails(row) {
      // 处理修改的逻辑
      this.reset();
      const id = row.id;
      this.isAdd = false;
      getGood(id).then((response) => {
        if (
          response.data.specificationsList &&
          response.data.specificationsList.length != 0
        ) {
          response.data.paramsNewArr = this.revertData(
            response.data.specifications
          );
          // response.data.specificationsList.map(el => {
          //   response.data.paramsNewArr.push({
          //     paramsName: el.split(',')[0],
          //     paramsValue: el.split(',')[1],
          //   })
          // })
        } else {
          response.data.paramsNewArr = [{ paramsName: "", paramsValue: "" }];
        }
        this.goodform = response.data;
        this.addOpen = true;
        if (row.parentId === 0) {
          this.title = "修改店铺商品";
        } else {
          this.title = "修改商品规格";
        }
      });
    },

    /** 补货的 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.form.classOneName = this.goodclassifyList.filter(item => item.id == this.form.classOneId)[0].deptName;
          // this.form.classTwoName = this.goodclassifyList.filter(item => item.id == this.form.classTwoId)[0].deptName;
          // this.form.classThreeName = this.goodclassifyList.filter(item => item.id == this.form.classThreeId)[0].deptName;

          if (this.form.id != null) {
            console.log(this.form, "form````````````````");
            if (this.form.source == 2) {
              //店铺自加
              let params = {
                id: this.form.id,
                counts: this.form.counts,
                remark: this.formNaNpxark,
              };
              replenishment(params).then((res) => {
                if (res.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else if (this.form.source == 1) {
              // 采购加入
              let params = {
                storeId: this.form.storeId,
                counts: this.form.counts,
                deliveryType: 1, //写死的普通配送
                deliveryCost: "0", //写死的配送费
                remark: this.formNaNpxark,
                goodIds: this.form.goodId,
              };
              replenish(params).then((res) => {
                if (res.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          } else {
            addGood(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    ////// 修改的确定
    transformgoodform(references) {
      return references
        .map((ref) => `${ref.paramsName},${ref.paramsValue || " "}`)
        .join(";");
    },
    transformFormData(references) {
      // 用于存储合并后的数据
      const mergedData = {};
      // 遍历原始数据数组
      references.forEach((item) => {
        if (mergedData[item.paramsName]) {
          // 如果该 paramsName 已存在，将 paramsValue 追加到已有值后面
          mergedData[item.paramsName].push(item.paramsValue);
        } else {
          // 如果该 paramsName 不存在，初始化一个数组存储 paramsValue
          mergedData[item.paramsName] = [item.paramsValue];
        }
      });

      const result = [];
      // 遍历合并后的数据对象
      for (const key in mergedData) {
        if (mergedData.hasOwnProperty(key)) {
          // 将 paramsName 和合并后的 paramsValue 按指定格式拼接
          result.push(`${key}:${mergedData[key].join(",")}`);
        }
      }
      return result.join("。");
    },
    goodsubmitForm() {
      console.log(888888, this.goodform);
      this.$refs.goodform.validate((v) => {
        if (v) {
          if (this.title.includes("店铺商品")) {
            this.goodform.classOneName = this.goodclassifyList.find(
              (item) => item.id == this.goodform.classOneId
            ).deptName;
            this.goodform.specifications = this.transformFormData(
              this.goodform.paramsNewArr
            );
          }
          // this.goodform.classTwoName = this.goodclassifyList.filter(item => item.id == this.goodform.classTwoId)[0].deptName;
          // this.goodform.classThreeName = this.goodclassifyList.filter(item => item.id == this.goodform.classThreeId)[0].deptName;

          if (this.isAdd) {
            addstoreGood(this.goodform).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.addOpen = false;
                this.getList();
                // this.$router.go()
              }
            });
          } else {
            updatastoreGood(this.goodform).then((res) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.addOpen = false;
              this.getList();
              // this.$router.go()
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除店铺商品：" + row.goodName + "？")
        .then(function () {
          return delGood(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "fx/store/good/export",
        {
          ...this.queryParams,
          goodIds: this.goodIds.join(","),
        },
        `good_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style>
.highlight-row {
  background-color: #f9f8ebc9;
  /* 需要变色的背景色 */
}
</style>
